/**
 * 
 */
package it.unitn.testbed.server.task;

import it.unitn.testbed.server.serial.SerialReceiver;

import java.util.Date;
import java.util.TimerTask;

import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

/**
 * Denotes an object that performs task cleanup.
 * 
 * @author Stefan Guna
 * 
 */
public class TaskTerminator extends TimerTask {
	public static Logger log = Logger.getLogger(TaskTerminator.class.getName());

	private Task task;

	public TaskTerminator(Task task) {
		this.task = task;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.TimerTask#run()
	 */
	@Override
	public void run() {
		SerialReceiver receiver = task.getReceiver();
		log.info("Task completed, closing packet sources (if existing).");
		if (receiver != null)
			receiver.terminate();
		sendStopReport();
	}

	/** Sends an email report with the status at the task termination. */
	private void sendStopReport() {
		StringBuffer buf = new StringBuffer();
		buf.append(task.toString() + " stopped on " + new Date() + "\n\n");

		try {
			MimeMessage msg = task.getGenericMsg();
			msg.setSubject(toString() + " stopped");
			msg.setText(buf.toString());
			Transport.send(msg);
		} catch (AddressException e) {
			log.error("Unable to recognize email address: " + e.getMessage());
		} catch (MessagingException e) {
			log.error("Unable to send email: " + e.getMessage());
		}
	}
}
